<?php
namespace control;

// 模具模具组合
class moldPortfolioClass extends adIndexClass
{
	private const page        = 'moldPortfolio';
	private const table       = 'mold_portfolio';
	private const tableMx     = 'mold_portfolio_detail';
	private const tableRecord = 'inventory_record';
	private const title       = '模具模具组合';
	private const state       = ['启用', '停用'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'code'          => [
                        'name'  => "组合编码",
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '组合名称',
                        'width' => 250,
                    ],
                    'mold'         => [
                        'name'  => '模具',
                        'width' => 250,
                    ],
                    'stid'          => [
                        'name'  => '创建人',
                        'width' => 250,
                    ],
                    'time'          => [
                        'name'  => '创建时间',
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "组合编码"   => text(array("name" => "code")),
                    "组合名称"   => text(array("name" => "name")),
                    "模具"   => text(array("name" => "moldName")),
                ],
                [
                    "创建时间"   => text(['name' => 'time', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 列表-查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 列表-查询结果
	 *
	 * @return bool|string
	 */
	public function homeSearch(): string
	{
		//查询结果
		$where = '';
		$equal = [
			'coid'  => self::$coid,
			'state' => $this->post('state'),
		];
		$like  = [
			'code' => $this->post('code'),
			'name' => $this->post('name'),
		];
		if ($this->post('moldName')) {
			$where .= "mdid IN (SELECT id FROM mold WHERE coid = '" . self::$coid . "' AND name like '%" . $this->post('moldName') . "%' AND state ='启用') ";
		}
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('time')) {
			$where .= self::timeComparison($this->post('time'));
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = [
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
				"edit"   => $array['state'] !== '已确认' ? ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"] : [],
			];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'mold':
                        $mold     = query('mold', " id = '$array[mdid]' ", 'name');
                        $row[] = $mold['name'];
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	/**
	 *选择生产模具
	 *
	 * @return bool|string
	 */
	public function addPortfolio(): bool|string
	{
		$html   =
			select(["name" => "type", "title" => "分类", "option" => explode('，', para('moldType'))]) .
			text(["name" => "code", "title" => "模具编码"]) .
			text(["name" => "moldName", "title" => "模具名称"]) .
			text(["name" => "model", "title" => "规格型号"]);
		$button = "<input style='margin-left: 5px' onclick=\"addPortfolio()\" type='button' class='searchSub' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(["title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button]);
	}

	/**
	 *添加模具
	 */
	public function addPortfolioSearch(): bool|string
	{
		$like  = [
			'name'  => $this->post('moldName'),
			'code'  => $this->post('code'),
			'model' => $this->post('model'),
		];
		$equal = [
			'type'  => $this->post('type'),
			'state' => '启用',
			'coid'  => self::$coid,
		];
		$where = search(["like" => $like, "=" => $equal]);
		$page  = $this->page([
			"table" => 'mold',
			"field" => "*",
			"where" => $where,
			"order" => "time ASC",
		]);
		//获取表头
		$tr[] = ['', '分类', '模具编码', '模具名称', '规格型号'];
		//获取记录
		foreach ($page['array'] as $array) {
			$tr[] = array(
				"<input name='mxId' value='$array[id]' type='radio' class='radio-bigger'>",
				$array['type'],
				$array['code'],
				$array['name'],
				$array['model'],
			);
		}
		$json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addPortfolioEdit(): bool|string
	{
		$mdid = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mdid)) {
			$json['warn'] = '请选择模具';
		} else {
			$mold = query('mold', "id = '$mdid' ");
			$json = [
				'warn' => 2,
				'res'  => [
					'name' => $mold['code'] . '-' . $mold['name'] . '-' . $mold['model'],
					'mdid' => $mold['id'],
				],
			];
		}
		return json_encode($json, 320);
	}


	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id       = $this->get('id');
		$info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
		$button[] = [
			'style' => 'li-btn-blue-bg',
			"name"  => "保存",
			"type"  => "点击事件",
			"title" => "保存",
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
		$tr[]     = ['', '产品编码', '产品名称', '规格型号', '单位', '穴数', '备注'];
		$result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
		foreach ((array)$result['array'] as $k=>$array) {
			$material    = query('material', " id = '$array[materialId]'");
			$tr[]        =
				[
                    componentClass::tablePperation($k+1,"delTableRow(this)").
					hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
					hidden(['name' => 'materialId[]', 'value' => $array['materialId'],]),
					$material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
					text(['name' => 'mxNum[]', 'value' => $array['num']]),
					text(['name' => 'mxText[]', 'value' => $array['text'],]),
				];
		}
		$list  = $this->listTable(['tr' => $tr, 'end' => true]);
		$page  = self::page;
        $tableBut = <<<EOT
		    <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())">选择产品</span>
            <span class="smallButton hidden" onclick="layer('{$this->get('cla')}','addMx',$('form[name=inventoryEditForm]').serialize())">保存盘点结果</span>
EOT;

		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '组合名称' => text(['name' => 'name', 'value' => $info['name'], 'title' => '组合名称']),
                    must . '模具' => hidden(['name' => 'mdid', 'value' => $info['mdid']])
                        . '<span id="moldName">' . ($info['mdid'] ? query('mold', "id = '$info[mdid]'", 'name')['name'] : '未选择') . '</span>'
                        . "<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addPortfolio',{})\" style='margin-left: 10px'>选择</span>",
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'moldPortfolioTable',
            'title' => '选择明细',
            'button' => $tableBut,
            'html' => $list,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
		]);
		$data['html'] .= <<<EOT
		<script>
		//选择明细
		function addRow(){
			$.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
				$("#moldPortfolioTable tbody").append(res.html);
				resetNumber($("#moldPortfolioTable"))
			},'json');
		}
        function addPortfolio(){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addPortfolioEdit', $("form[name='mxForm']").serialize(),function(resp) {
	         if (resp.warn === 2){
	            $('#moldPortfolioAddPortfolio').hide();
	            $("[name='mdid']").val(resp.res.mdid);
	            $("#moldName").html(resp.res.name);
	         }else{
	             msg(res.warn);
	         }
	        },'json');
        }
        
		</script>
EOT;
		//返回
		return $this->tab($data);
	}

	public function editEdit(): bool|string
	{
		$id               = $this->post('id') ?: self::getId();
		$materialIdArr = $this->post('materialId');
		$mxIdArr          = $this->post('mxId');
		$mxNumArr         = $this->post('mxNum');
		$mxTextArr        = $this->post('mxText');
		$field            = [
			'mdid' => $this->post('mdid'),
			'name' => $this->post('name'),
			'text' => $this->post('text'),
		];
		$annotation       = [
			'mdid' => '模具',
			'name' => '名称',
			'text' => '备注',
		];
		$rules            = [
			'mdid' => 'required',
			'name' => 'required',
		];
		$vt               = new \verify();
		$result           = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " coid = '" . self::$coid . "' AND id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($mxIdArr)) {
			$json['warn'] = '请选择组装明细';
		} elseif (static::is_null_array($mxNumArr)) {
			$json['warn'] = '数量请填写完整';
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'MJ' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'code',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'    => $id,
					'code'  => $orderNo,
					'state' => '启用',
					'coid'  => self::$coid,
					'stid'  => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			//添加或更新报价单明细
			if (is_array($mxIdArr)) {
				foreach ($mxIdArr as $k => $nid) {
					$mx          = query(self::tableMx, "id = '$nid'");
					if (!empty($mx['id'])) {
						$warn = static::update([
							"table" => self::tableMx,
							"field" => [
								'coid'          => self::$coid,
								'materialId'    => $materialIdArr[$k],
								'num'           => $mxNumArr[$k],
								'text'          => $mxTextArr[$k],
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => self::tableMx,
							"field" => [
								'id'            => $nid,
								'coid'          => self::$coid,
								'orderId'       => $id,
                                'materialId'    => $materialIdArr[$k],
								'num'           => $mxNumArr[$k],
								'text'          => $mxTextArr[$k],
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass       = false;
						$json['warn'] = $warn;
						break;
					}
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/**
	 * @return bool|string
	 */
	public function addMx(): bool|string
	{
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(["name" => "supplyControl", "value" => '允许采购']) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit(): bool|string
	{
		$mxIdArr = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = '请选择产品';
		} else {
            $tr = [];
			foreach ($mxIdArr as $mxId) {
				$material    = query('material', "id = '$mxId'");
				$hideStr     = hidden(['name' => 'mxId[]', 'value' => self::getId()]) . hidden(['name' => 'materialId[]', 'value' => $mxId,]);
                $tr[]        =
                    [
                        componentClass::tablePperation('',"delTableRow(this)").
                        $hideStr,
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        text(['name' => 'mxNum[]', 'value' => '']),
                        text(['name' => 'mxText[]', 'value' => '']),
                    ];
			}
			$json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
		}
		return json_encode($json, 320);
	}

	/**
	 * 详细
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data     = [
				"id" => $info['id'],
			];
			$button[] = [
				"name"  => "编辑",
				"type"  => "顶部页卡",
				"title" => "编辑用户",
				"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
				'style' => 'li-btn-blue-bg',
			];
			//按钮
			$button[] = [
				"name" => "删除",
				"type" => "弹出层",
				"cla"  => $this->get('cla'),
				"fun"  => "operate",
				"post" => ["act" => 'del', "id" => $info['id']],
			];
			$mxtr[]   = ['产品编码', '产品名称', '规格型号', '单位', '穴数', '备注'];
			$result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
			foreach ($result['array'] as $array) {
				$material    = query('material', " id = '$array[materialId]'");
				$mxtr[]      = [
					$material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    $array['num'],
                    $array['text']
				];
			}
			$mold = query('mold', "id = '{$info['mdid']}'");
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				[
					[
						"组合件" => $info['name'],
						"模具"  => $mold['code'] . '-' . $mold['name'] . '-' . $mold['model'],
                        "单据编号" => $info['code'],
                        "制单人"  => self::findStaff($info['stid']),
					],
                    [
                        "状态"   => $info['state'],
                    ],
					[
						"备注" => pre($info['text']),
					],

				],
			]);
            $data['html'] .= $this->detailList([
                'title' => '子件',
                'html' => $this->listTable(['tr' => $mxtr, 'showSort' => true]),
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}


	// 操作中转
	public function operate(): string
	{
		$act   = $this->post('act') ?? '';
		$pwd   = $word = false; // 需要密码
		$power = '';
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = '确认';
				$title    = '是否已确认此模具模具组合，确认后将不可修改？';
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';

				$word = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = '编辑';
				$title    = '是否确认提交此模具模具组合？';
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';

				$word = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = '撤回';
				$title    = '是否确认取消此模具模具组合？';
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';

				$word = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';

				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): string|false
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} else {
			if (empty($array)) {
				$json['warn'] = "你一个数据都没有选择呢";
			} else {
				$text  = "";
				$x     = 0;
				$array = is_array($array) ? $array : [$array];
				foreach ($array as $id) {
					$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
					if ($info['state'] == '已确认') {
						$warn = "删除失败：已确认，暂不能删除";
					} else {
						//最后删除基本参数
						delete(array("table" => self::table, "where" => " id = '$id' "));
						delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
						delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
						//返回
						$warn = "删除成功";
						$x++;
					}
					$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
				}
				//添加日志
				$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
				$this->logText(array("type" => self::page, "text" => $text));
				$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
			}
		}
		return json_encode($json, 320);
	}

}
